import scrapy
from scrapy import Request, FormRequest
import time


class GithubSpider(scrapy.Spider):
    name = 'login2'
    allowed_domains = ['github.com']

    #

    def start_requests(self):
        # 重写start_requests方法
        urls = ['https://github.com/login']
        for url in urls:
            yield scrapy.Request(url, meta={'cookiejar': 1}, callback=self.github_login)
            # 通过meta传入cookiejar特殊key，爬取url作为参数传给回调函数
            # meta：字典格式的元数据
            # cookiejar：是meta的一个特殊的key，通过cookiejar参数可以支持多个会话对某网站进行爬取
            # 可以对cookie做标记1, 2, 3, 4......这样scrapy就维持了多个会话

    def github_login(self, response):
        print("cookiejar", response.meta["cookiejar"])
        # 获取三个关键信息
        authenticity_token = response.xpath("//input[@name='authenticity_token']/@value").extract()[0]
        timestamp_secret = response.xpath("//input[@name='timestamp_secret']/@value").extract()[0]
        timestamp = response.xpath("//input[@name='timestamp']/@value").extract()[0]
        # form_data表单数据
        form_data = {
            "commit": "Sign in",
            "authenticity_token": authenticity_token,
            "ga_id": "285586600.1585549705",
            "login": "952302908@qq.com",
            "password": "extreme123",
            "webauthn-support": "supported   ",
            "webauthn-iuvpaa-support": "unsupported",
            "return_to": "",
            "required_field_6f62": "",
            "timestamp": timestamp,  # str(int(time.time() * 1000))
            "timestamp_secret": timestamp_secret,
        }
        return scrapy.FormRequest(
            url='https://github.com/session',
            meta={'cookiejar': response.meta['cookiejar']},
            formdata=form_data,
            callback=self.vertify_login,
        )
        # return scrapy.FormRequest.from_response(
        #     response,
        #     url='https://github.com/session',
        #     meta={'cookiejar': response.meta['cookiejar']},
        #     headers=self.headers,
        #     formdata=form_data,
        #     callback=self.github_after,
        # )

    def vertify_login(self, response):
        print(response.meta["cookiejar"])
        if 'yozuriha' in response.body.decode():
            self.logger.info('登录成功！')
            # 如果含有“Browse activity”，则打印登录成功
        else:
            self.logger.error('登录失败！')
